<template>
  <view class="content">
    <tui-form ref="formRef" :show-message="false" :model="formData">

      <tui-form-item labelWidth='180' asterisk label="检查编号" prop="qualityCode" >
        <tui-input padding="0" :borderBottom="false" v-model="formData.qualityCode" placeholder="请输入"></tui-input>
      </tui-form-item>
      
      
      <!-- 检查分类 -->
      <tui-form-item arrow labelWidth='180' asterisk label="检查分类" prop="qualityTypeName" @click="popupShow=true">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.qualityTypeName" placeholder="请选择"></tui-input>
      </tui-form-item>
      <tui-picker :show="popupShow" :pickerData="itemList" @hide="popupShow=false" @change="change"></tui-picker>
      
      <tui-form-item  labelWidth='180' asterisk label="检查部位" prop="qualityPart">
        <tui-input padding="0"  :borderBottom="false" v-model="formData.qualityPart" placeholder="请输入"></tui-input>
      </tui-form-item>
      
      <!-- 检查人员 -->
      <tui-form-item arrow labelWidth='180' asterisk label="检查人员" prop="qualityMember" @click="popupShow2=true">
        <tui-input padding="0" :disabled='true' :borderBottom="false" v-model="formData.qualityMember" placeholder="请输入"></tui-input>
      </tui-form-item>
      <tui-select :list="itemList2" multiple reverse :show="popupShow2" @confirm="confirm2" @close="close"></tui-select>
      
      <tui-form-item labelWidth='180' asterisk label="检查情况" prop="qualityDescription">
        <tui-input padding="0" :borderBottom="false" v-model="formData.qualityDescription"
          placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 验收日期 -->
      <tui-form-item arrow labelWidth='180' asterisk label="检查时间" prop="qualityTime">
        <tui-input padding="0" :borderBottom="false" :disabled='true' v-model="formData.qualityTime"
          placeholder="请选择"></tui-input>
      </tui-form-item>

      <tui-form-item labelWidth='180' asterisk label="检查结果" prop="isPass">
        <tui-input padding="0" :borderBottom="false" v-model="formData.isPass" placeholder="请输入"></tui-input>
      </tui-form-item>
      <!-- 上传附件 -->
      <tui-form-item labelWidth='180' asterisk label="上传图片" prop="files">
        <tui-upload :value='value' @getFileId='getFileId' :serverUrl="serverUrl" @complete="completeUpload"
          @remove="remove"></tui-upload>
      </tui-form-item>
      <view style="padding:0 10px 10px 10px;">
        <tui-form-button text="提交" @click="submit"></tui-form-button>
      </view>
    </tui-form>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, onMounted } from 'vue';
  import { deleteQualityFile2, getQualityById, selectQualityById, updateQuality, uploadQualityAttach, addQuality, getQualityTypeList, getQualityMemberNameList, getQualityMemberIdList } from '@/apis/quality.js';
  const popupShow = ref(false)
  const popupShow2 = ref(false)
  const itemList = ref([])
  const itemList2 = ref([])
  const formRef = ref(null);
  const calendar = ref(null);
  const serverUrl = 'http://192.168.1.127:8086/project-lot/uploadProjectLotAttach'
  const imageList = ref([])
  const pendingDeleteFiles = ref([])
  const value = ref([])
  const initEndDate = ref('')
  const initStartDate = ref('')

  const rules = [
    {
      name: "qualityCode",
      rule: ["required"],
      msg: ["请输入检查编号"]
    }, {
      name: "qualityTypeName",
      rule: ["qualityTypeName"],
      msg: ["请选择检查分类"]
    }, {
      name: "qualityPart",
      rule: ["required"],
      msg: ["请输入检查部位"]
    }, {
      name: "qualityMember",
      rule: ["required"],
      msg: ["请选择检查人员"]
    }, {
      name: "qualityDescription",
      rule: ["required"],
      msg: ["请输入检查情况"]
    }, {
      name: "qualityTime",
      rule: ["required"],
      msg: ["请选择检查时间"]
    }, {
      name: "isPass",
      rule: ["required"],
      msg: ["请选择检查结果"]
    }];

  const formData = ref({
    fileIds: [],
    isPass: '',
    projectId: 0,
    qualityCode: "",
    qualityDescription: "",
    qualityMemberIdList: [],
    qualityMember:'',
    qualityPart: "",
    qualityTime: "",
    qualityType: '',
    qualityTypeName: '',
    qualityUnitsId: 0
  })

  const projectId = uni.getStorageSync('projectInfo').id
  const isEdit = ref(false)
  const Qualityid = ref(0)

  onMounted(() => {
    getList()
  });

  onLoad(({ lotId }) => {
    //   //如果有lotId就是编辑状态 再次提交时发起重新送审
    //   //添加一个状态判断编辑还是新增
    isEdit.value = false
    if (lotId) {
      Qualityid.value = lotId
      isEdit.value = true
      pendingDeleteFiles.value = []
      getFullProjectLotInfoById(lotId).then(res => {
        console.log(res.data.data);
        let data = res.data.data
        formData.value = data

      })
    }
  })
  
  //检查分类
  const hide=(e)=>{
    console.log(e);
  }
  const change=(e)=>{
    formData.value.qualityTypeName=e.text
    console.log(e);
  }
  //检查人员
  const confirm2=(e)=>{
    formData.value.qualityMember=e.options.map(e=>e.text).join(',')
    popupShow2.value=false
  }
  const close=()=>{
    popupShow2.value=false
  }



  //文件上传功能
  const completeUpload = (e) => {
    imageList.value = e.imgArr;
  }

  const remove = (e) => {
    pendingDeleteFiles.value.push(formData.value.fileIds[e.index])
    formData.value.fileIds.splice(e.index, 1)
  }

  const getFileId = (value) => {
    formData.value.fileIds.push(value.fileId);
  }

  //获取列表数据
  const getList = async () => {
    let res = await getQualityTypeList()
    itemList.value = res.data.data.map((e, i) => ({ text: e, value: i }))
    let res2 = await getQualityMemberNameList(projectId)
    itemList2.value = res2.data.data.map(e => ({ text: e.userName, value: e.userId }))
  }

  //转换格式
  const handleData = (data) => {
    return data.map(item => ({
      text: item.nodeName,
      value: item.id,
      children: item.children ? handleData(item.children) : null
    }));
  }


  //提交表单
  const submit = async (values) => {
    console.log(formData.value);
    if (isEdit.value === false) {
      //新增
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.fileIds.length > 0) {
            addQuality(projectId, formData.value).then(res => {
              if (res.data.code === 200) {
                uni.navigateTo({
                  url: '/pages/qualityCheck/qualityCheck'
                })
                // plus.nativeUI.toast("新增成功");
              }
            })
          } else {
            plus.nativeUI.toast("请上传图片");
          }
        })
      }
    } else {
      console.log(formData.value);

      //编辑
      if (formRef.value) {
        formRef.value.validate(formData.value, rules, true).then((res) => {
          if (res.isPass && formData.value.fileIds.length > 0) {
            // 删除已缓存的附件
            if (pendingDeleteFiles.value.length > 0) {
              deleteQualityFile2(pendingDeleteFiles.value).then(res => {
                console.log('删除成功');
              })
            }
            formData.value.projectLotFileList = formData.value.fileIds.map(e => ({ id: e }))
            updateQuality(formData.value).then(res => {
              if (res.data.code === 200) {
                uni.navigateTo({
                  url: '/pages/qualityCheck/qualityCheck'
                })
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    background-color: #fff;
    // padding: 0px 10px 10px 10px;
  }
</style>